import React, { Component } from 'react';
import { View } from '@tarojs/components';
import { AtTabs, AtTabsPane, AtList, AtListItem, AtButton, AtNavBar, AtNoticebar } from "taro-ui";
import Taro from '@tarojs/taro';
import "./approvedetail.less";
import config from '../../config.json'
import { formatDate } from '../../modal/modal';
import { ApproveStatusText } from '../../modal/component';


interface AgreedData {
    id: string
    aid: number
    uid: string
    mid: number
    start_time: number
    end_time: number
    reason: string
    note: string
    status: string
    approver: string //审批人
    group?: number
    area: number
    authority: number
    department: string
    mname: string
    uname: string
    wifi: number
    projector: number
    phone: string
    anote: string
    unote: string
}

interface ApproveDetailState {
    data: AgreedData
    disabled: boolean
    conflict: any[]
}


export default class ApproveDetail extends Component<any, ApproveDetailState> {
    constructor(props) {
        super(props);
        this.state = {
            data: {} as AgreedData,
            disabled: false,
            conflict: []
        }
    }


    async componentWillMount() {

    }

    componentDidMount() { }

    componentWillUnmount() { }

    async componentDidShow() {
        let _this = this;
        let data;
        let conflict = Taro.getStorageSync("conflict");
        console.log(conflict)
        if (conflict) {
            data = conflict;
            Taro.removeStorageSync("conflict")
        } else {
            data = Taro.getStorageSync("approve_detail");
        }
        if (data) {
            this.setState({
                data: JSON.parse(data)
            });
            data = JSON.parse(data);
            let res = await Taro.request({
                url: config.domainName + "/agreed/getConflict",
                header: {
                    "token": Taro.getStorageSync("token")
                },
                data: {
                    mid: data.mid,
                    start_time: data.start_time,
                    end_time: data.end_time,
                    aid: data.aid
                }
            });
            this.setState({
                conflict: res.data.data
            });
        } else {
            Taro.navigateTo({ url: "/pages/approve/approve" })
        }
    }

    componentDidHide() { }

    onPass() {
        let _this = this;
        if (this.state.conflict.length) {
            Taro.showToast({
                title: "无法通过，请先处理冲突",
                icon: "none"
            })
        } else {
            Taro.showModal({
                title: '提示',
                content: '通过后与此申请冲突的其他申请会自动拒绝，确定吗？',
                async success(res) {
                    if (res.confirm) {
                        _this.setState({ disabled: true })
                        Taro.showLoading({ title: "正在操作..." });
                        let res = await Taro.request({
                            url: config.domainName + "/agreed/aprove",
                            method: "POST",
                            data: { action: "pass", aid: _this.state.data.aid },
                            dataType: "json",
                            header: {
                                "token": Taro.getStorageSync("token")
                            }
                        })
                        let response = res.data;
                        Taro.hideLoading();
                        if (!response.code) {
                            Taro.showToast({ title: "操作成功", icon: "success" });
                            setTimeout(() => {
                                Taro.navigateBack();
                            }, 1500)
                        } else {
                            Taro.showToast({ title: "操作失败：" + response.msg, icon: "error" as any });
                            _this.setState({ disabled: false })
                        }
                    } else if (res.cancel) {
                        console.log('用户点击取消')
                    }
                }
            })
        }
    }

    onRefuse() {
        let _this = this;
        Taro.showModal({
            title: '提示',
            content: '确定要拒绝吗？',
            async success(res) {
                if (res.confirm) {
                    try {
                        _this.setState({ disabled: true });
                        Taro.showLoading({ title: "正在操作..." });
                        let res = await Taro.request({
                            url: config.domainName + "/agreed/aprove",
                            method: "POST",
                            data: { action: "refuse", aid: _this.state.data.aid },
                            header: {
                                "token": Taro.getStorageSync("token")
                            }
                        })
                        let response = res.data;
                        Taro.hideLoading();
                        if (!response.code) {
                            Taro.showToast({ title: "操作成功", icon: "success" });
                            setTimeout(() => {
                                Taro.navigateBack();
                            }, 1500)
                        } else {
                            Taro.showToast({ title: "操作失败：" + response.msg, icon: "error" as any });
                            _this.setState({ disabled: false })
                        }
                    } catch {
                        Taro.hideLoading();
                        Taro.showToast({
                            title: "出现异常",
                            icon: "none"
                        });
                    }
                } else if (res.cancel) {
                    console.log('用户点击取消')
                }
            }
        })

    }

    render() {
        return (
            <View style={{ marginBottom: "2rem" }}>
                <AtNavBar
                    onClickLeftIcon={() => { Taro.navigateBack() }}
                    color='#000'
                    title='审批'
                    leftIconType="chevron-left"
                />

                <View style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginRight: "20px" }}>
                    <View className="module-title">申请信息</View>
                </View>

                <View className="informs">
                    {this.state.conflict.length ? <View onClick={() => {

                        Taro.setStorageSync("conflict", JSON.stringify(this.state.conflict[0]));
                        Taro.navigateTo({ url: "/pages/approvedetail/approvedetail" });
                    }}><AtNoticebar>该申请与已通过的申请有冲突，点击查看冲突项</AtNoticebar></View> : ""}
                    <View className="informs-item">日期：{getDate(this.state.data.start_time)}</View>
                    <View className="informs-item">时间：</View>
                    <View
                        className="time"
                        style={{
                            display: "flex",
                            alignItems: "center",
                            justifyContent: "center"
                        }}
                    >
                        <View className="hour-min">{formatDate(new Date(this.state.data.start_time), "HH:mm")}</View>
                        <div style={{
                            width: "2rem",
                            height: "3px",
                            backgroundColor: "#222"
                        }}></div>
                        <View className="hour-min">{formatDate(new Date(this.state.data.end_time), "HH:mm")}</View>
                    </View>
                    <View className="informs-item">状态：<ApproveStatusText status={this.state.data.status} /></View>
                    <View className="informs-item">理由：{this.state.data.reason}</View>
                    <View className="informs-item">备注：{this.state.data.anote}</View>
                </View>

                <View style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginRight: "20px" }}>
                    <View className="module-title">申请人信息</View>
                </View>
                <View className="informs">
                    <View className="informs-item">名字：{this.state.data.uname} </View>
                    <View className="informs-item">系部：{this.state.data.department}</View>
                    <View className="informs-item">联系电话：{this.state.data.phone}</View>
                    <View className="informs-item">备注：{this.state.data.unote}</View>
                </View>
                {this.state.data.status === "wait" ? <View style={{ display: "flex", margin: "20px 0" }}>
                    <AtButton disabled={this.state.disabled} onClick={this.onRefuse.bind(this)} className="danger-btn block-btn">拒绝</AtButton>
                    <AtButton disabled={this.state.disabled} onClick={this.onPass.bind(this)} className="block-btn" type="primary">通过</AtButton>
                </View> : ""}
                {this.state.data.status === "pass" && this.state.data.start_time > new Date().getTime() ? <AtButton disabled={this.state.disabled} onClick={this.onRefuse.bind(this)} className="danger-btn m-block-btn">改为不通过</AtButton> : ""}
            </View>
        )
    }
}


function getDate(t: number): string {
    const stringDay = (n: number): string => {
        console.log(n)
        switch (n) {
            case 1:
                return "一";
            case 2:
                return "二";
            case 3:
                return "三";
            case 4:
                return "四";
            case 5:
                return "五";
            case 6:
                return "六";
            case 0:
                return "日";
        }
    }
    let time = new Date(t);
    let now = new Date();
    let year = time.getFullYear();
    let month = time.getMonth() + 1;
    let date = time.getDate();
    let day = time.getDay();
    let hour = time.getHours();
    let min = time.getMinutes();

    let str = "";
    if (now.getFullYear() === year && now.getMonth() + 1 === month && date - now.getDate() < 2 && date - now.getDate() >= 0) {
        switch (date - now.getDate()) {
            case 0:
                str = "（今天）";
                break;
            case 1:
                str = "（明天）";
                break;
        }
    }

    return `${year}年${month}月${date}日 星期${stringDay(day)}${str}`;
}